﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TemplatesPrint.DBHelper;
using TemplatesPrint.Entitys;

namespace TemplatesPrint.Views
{
    public partial class FrmJiaMengDian : UIPage
    {
        string _type = "";
        string _qryTxt = "";
        public decimal amount = 0;
        public FrmJiaMengDian(string type="", string qryTxt="")
        {
            InitializeComponent();
            _type = type;
            _qryTxt = qryTxt;
        }

        private void FrmClientInfo_Initialize(object sender, EventArgs e)
        {
            udgvJiaMengDianList.MultiSelect = true;
            udgvJiaMengDianList.SelectionMode = DataGridViewSelectionMode.CellSelect;
           
            LoadInfo();
            SetColumnSortMode();
            uiPagination1.PageSize = 50;
            QryInfos(1, uiPagination1.PageSize, _qryTxt.Trim());
        }


        void LoadInfo()
        {
            if (_type == "main")
            {
                panel1.Visible=false;

                udgvJiaMengDianList.RowsDefaultCellStyle.Font = new Font("宋体", 9); // 设置字体为 Arial，大小为 12
                udgvJiaMengDianList.ColumnHeadersDefaultCellStyle.Font = new Font("宋体", 9); // 设置字体为 Arial，大小为 12
            }
        }
        private void QryInfos(int pageIndex, int pageSize, string txt)
        {
            using (var db = SQLiteHelper.GetInstance())
            {
                int totalCount = 0;
                var selecter = db.Queryable<SchemeEntity>()
                   .Where(x => x.SchemeType == "加盟店");
                if (_type == "main")
                {
                    selecter.Where(e => e.Tel.Contains(txt) || e.Address.Contains(txt)
                    || e.DirectPushTeacher.Contains(txt) || e.TwoTeacher.Contains(txt)
                    || e.TwoDirector.Contains(txt) || e.OneDirector.Contains(txt)
                    || e.RegionalAgent.Contains(txt) || e.JoiningScheme.Contains(txt));
                }
                else
                {
                    selecter.Where(e => e.Tel.Contains(txt) || e.xName.Contains(txt) || e.Address.Contains(txt)
                   || e.DirectPushTeacher.Contains(txt) || e.TwoTeacher.Contains(txt)
                   || e.TwoDirector.Contains(txt) || e.OneDirector.Contains(txt)
                   || e.RegionalAgent.Contains(txt) || e.JoiningScheme.Contains(txt));
                }
                var Amount = selecter.Sum(x => x.Amount);

                var i = 1;
                var tasks = selecter.OrderBy(x => x.CreateTime).Mapper((it, cache) =>
                {
                    it.JoiningTime = DateTime.Parse(it.JoiningTime.Value.ToString("yyyy-MM-dd"));
                    it.JoiningScheme = $"{it.JoiningScheme}  (金额:{it.Amount})";
                    it.Num = (pageIndex - 1) * pageSize + i;
                    i++;
                }).ToPageList(pageIndex, pageSize, ref totalCount);
               
                udgvJiaMengDianList.DataSource = tasks;
                uiPagination1.TotalCount = totalCount;
                amount = Amount;
                ulabCount.Text = $"金额:{Amount}";
            };
            
        }

        private void uiPagination1_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            QryInfos(pageIndex, count, utxtQry.Text.Trim());
        }

        private void usbtnQry_Click(object sender, EventArgs e)
        {
            QryInfos(1, uiPagination1.PageSize, utxtQry.Text.Trim());
        }

        private SchemeEntity DgvSelected()
        {
            SchemeEntity scheme = null;
            int rows = this.udgvJiaMengDianList.SelectedCells.Count;
            if (rows ==1)
            {
                var rowIndex = this.udgvJiaMengDianList.SelectedCells[0].RowIndex;
                var id = this.udgvJiaMengDianList.Rows[rowIndex].Cells["Id"].Value.ToString();
                using (var db = SQLiteHelper.GetInstance())
                {

                    scheme = db.Queryable<SchemeEntity>()
                        .Where(x => x.Id == int.Parse(id))
                        .First();
                };
            }
            else
            {
                ShowInfoDialog("请先选择需要操作的数据！");
            }
            return scheme;
        }

        private void tsbButton_Click(object sender, EventArgs e)
        {
            ToolStripButton tsb = (ToolStripButton)sender;
            switch (tsb.Name)
            {
                case "tsbCreate":
                    TsbCreate();
                    break;
                case "tsbDelete":
                    TsbDelete();
                    break;
                case "tsbEdit":
                    TsbEdit();
                    break;
            }
            QryInfos(1, uiPagination1.PageSize, utxtQry.Text.Trim());
        }

        void TsbCreate()
        {
            FrmCreate frmCreate = new FrmCreate("加盟店");
            frmCreate.ShowDialog();
        }
        void TsbEdit()
        {
            var schemeEntity= DgvSelected();
            if (schemeEntity!=null)
            {
                FrmCreate frmCreate = new FrmCreate("加盟店", schemeEntity);
                frmCreate.ShowDialog();
            }
            
        }

        void TsbDelete()
        {
            var schemeEntity = DgvSelected();
            if (schemeEntity != null)
            {
                DialogResult result = MessageBox.Show("是否确认删除此数据，删除后不可恢复?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    using (var db = SQLiteHelper.GetInstance())
                    {
                        db.Deleteable(schemeEntity).ExecuteCommand();
                    };
                    MessageBox.Show("删除成功!");
                }
            }
        }

        private void udgvJiaMengDianList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // 点击列头选中整列
            if (e.RowIndex == -1)
            {
                udgvJiaMengDianList.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
                udgvJiaMengDianList.Columns[e.ColumnIndex].Selected = true;//让此列立刻被选中

                var name = udgvJiaMengDianList.Columns[e.ColumnIndex].HeaderText;
                Thread.Sleep(100); // 等待一会确保内容已经复制到剪贴板

                SendKeys.SendWait("^c");
                Thread.Sleep(100); // 等待一会确保内容已经复制到剪贴板

                // 从剪贴板中获取复制的内容
                string selectedText = Clipboard.GetText().Replace($"{name}\r\n", "");
                Clipboard.SetText(selectedText);
                MessageBox.Show("此列已复制!");
            }
            else
            {
                udgvJiaMengDianList.SelectionMode = DataGridViewSelectionMode.CellSelect;
                udgvJiaMengDianList.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;//让此行立刻被选中
            }
        }

        void SetColumnSortMode()
        {
            foreach (var c in udgvJiaMengDianList.Columns)
            {
                (c as DataGridViewTextBoxColumn).SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
            }

        }
    }
}
